<template>
  <div class="openContainer2">
    <div class="commonTitle">
      <div class="commonTitleMain">
        <h2>排课</h2>
      </div>
    </div>
    <div class="cwBody" v-if="scheduleList.length">
      <div class="studentList">
        <ul>
          <li class="card" v-if="item.basic_info" v-for="item in scheduleList">
            <div class="courseMain2">
              <div class="courseDetail">
                <p>
                  <span>{{item.basic_info.name}}</span>
                  <span>{{item.basic_info.mobile | numHiding}}</span>
                </p>
                <p>
                  <span>{{item.subject_format}}</span>
                  <span>{{item.grade_format}}</span>
                  <span>{{item.textbook_format}}</span>
                </p>
              </div>
              <div class="enterRoom">
                <p class="enterClass" @click="arrangeClasses(item.id)">排课</p>
                <p class="enterClass" style="margin: 20px 10px;" @click="batchSchedule(item.id)">批量排课</p>
                <p class="enterClass enterClass2" @click="classRecord(item.id)">课次记录</p>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="courseListNull tip-null" v-else>
      <img src="../../assets/teacher/ai.png" alt="null">
      <span class="tip-null-text" style="font-size: 16px;color: #8d8d8d;">你还没有课程计划哦~</span>
    </div>
    <!--排课-->
    <Modal v-model="openClass" width="380" class="openClass" :mask-closable="false">
      <p slot="header">
        <span>排课</span>
      </p>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>
      <Form :model="formValidate" :label-width="70">
        <FormItem label="选择日期:">
          <DatePicker type="date"
                      :options="options"
                      placeholder="请选择"
                      v-model="formValidate.class_planned_date"
                      :clearable="false"
                      @on-change="isClick"></DatePicker>
        </FormItem>
        <FormItem label="开始时间:">
          <Cascader :data="startTimeData"
                    v-model="startTimeValue"
                    :clearable="false"
                    :render-format="label => label.join(' : ')"
                    @on-change="isClick"
                    style="width: 196px;"></Cascader>
        </FormItem>
        <FormItem label="上课时长:">
          <RadioGroup v-model="formValidate.duration" @on-change="isClick">
            <Radio label="45">45min</Radio>
            <Radio label="60">60min</Radio>
            <Radio label="90">90min</Radio>
            <Radio label="120">120min</Radio>
          </RadioGroup>
        </FormItem>
        <Button class="submit" type="primary" :disabled="isCheck" :class="{ active: isLoad }" :loading="loadingPaike"
                @click="handleSubmit">排课
        </Button>
      </Form>
      <p slot="footer"></p>
    </Modal>
    <!--批量排课-->
    <Modal v-model="batchScheduling" width="850" class="openClass openClass2" :mask-closable="false">
      <p slot="header">
        <span>批量排课</span>
      </p>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>
      <Form ref="batchValidate" :model="batchValidate" :rules="batchRule" :label-width="80">
        <FormItem label="选择需排课日期:" prop="date" :label-width="140">
          <DatePicker type="daterange" style="width: 200px"
                      :options="options"
                      placeholder="请选择排课日期"
                      :editable="false"
                      v-model="batchValidate.date"
                      @on-change="[batchValidate.date_range_left,batchValidate.date_range_right]=$event"
                      :clearable="false"></DatePicker>
        </FormItem>

        <div v-for="(item,index) in batchValidate.weeks" style="display: flex;justify-content: space-between">
          <FormItem label="星期" :label-width="50" :prop="'weeks.' + index + '.day_of_week'"
                    :rules="{required: true, type:'number',message: '请选择星期', trigger: 'change'}">
            <Select style="width: 100px;" v-model="item.day_of_week" placeholder="请选择">
              <Option v-for="(week,$index) in weekList" :key=$index
                      :value="parseInt(week.key)">{{week.value}}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="开始时间:" :prop="'weeks.' + index + '.start_time'"
                    :rules="{required: true, type:'array',message: '请选择开始时间', trigger: 'change'}">
            <Cascader :data="startTimeData"
                      v-model="item.start_time"
                      :clearable="false"
                      :render-format="label => label.join(' : ')" style="width: 100px;"></Cascader>
          </FormItem>
          <FormItem label="上课时长:" :prop="'weeks.' + index + '.duration'"
                    :rules="{required: true,message: '请选择上课时长', trigger: 'change'}">
            <RadioGroup v-model="item.duration">
              <Radio label="45">45min</Radio>
              <Radio label="60">60min</Radio>
              <Radio label="90">90min</Radio>
              <Radio label="120">120min</Radio>
            </RadioGroup>
          </FormItem>
          <p class="classOperate">
            <span @click="addClass">+添加</span>
            <span @click="deleteClass(index)">-删除</span>
          </p>
        </div>

        <Button class="submit" type="primary" @click="handleSubmit2('batchValidate')">排课</Button>
      </Form>
      <p slot="footer"></p>
    </Modal>
  </div>
</template>
<style lang="less">
  @import '../../style/openClass2.less';
</style>
<script>
  import {timestamp, forMatTime} from '@/common/js/common';
  import {apiBase2, apiBase3} from '@/common/js/api.config';

  const defaultForm = {  //初始化表单信息
    courseDate: '',
    courseStartTime: '',
    courseLength: '',
  };

  export default {
    data() {
      return {
        loadingPaike: false,
        startTimeValue: [],  //开始时间列表
        startTimeData: [],  //开始时间选中
        getStudentsUrl: this.$store.state.getStudents,
        arrangeCourse: this.$store.state.arrangeCourse,
        studentsList: [],  //学生列表
        openClass: false,  //排课弹窗
        isLoad: false,  //loading
        isCheck: true,  //是否不可点击
        formItem: Object.assign({}, defaultForm),
        options: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },


        getTeacherClassSchedules: this.$store.state.getTeacherClassSchedules,
        courseScheduling: this.$store.state.courseScheduling,
        scheduleList: [],
        formValidate: {
          id: "",
          class_planned_date: "",
          class_planned_start_time: "",
          class_planned_end_time: "",
          duration: ""
        },
        courseLength: "",
        //批量排课

        batchCourse: this.$store.state.batchCourse,
        batchScheduling: false,
        batchValidate: {
          class_schedule_id: "",
          date: [],
          date_range_left: "",
          date_range_right: "",
          weeks: [{
            day_of_week: "",
            start_time: [],
            duration: ""
          },
          ],
        },
        batchRule: {
          // date: [
          //   {
          //     required: true,
          //     type: "array",
          //     message: '选择需排课日期',
          //     trigger: 'change'
          //   }
          // ],
          date: [
            {
              type: 'array',
              required: true,
              message: '选择需排课日期',
              fields: {
                0: {type: 'date', required: true, message: '请选择起止日期'},
                1: {type: 'date', required: true, message: '请选择起止日期'}
              },
              trigger: 'change'
            }
          ],

        },
        weekList: [
          {key: "1", value: "一"},
          {key: "2", value: "二"},
          {key: "3", value: "三"},
          {key: "4", value: "四"},
          {key: "5", value: "五"},
          {key: "6", value: "六"},
          {key: "0", value: "日"},
        ],
      }
    },
    filters: {
      numHiding: function (value) {  // 电话号码****
        if (!value) return '';
        let r = value.substring(3, 7);
        return value.replace(r, '****');
      }
    },
    created() {
      let minutes = []
      for (let i = 0; i < 12; i++) {   //开始时间分钟 间隔五分钟
        let num = i * 5 < 10 ? `0${i * 5}` : `${i * 5}`
        minutes.push({
          value: num,
          label: num,
        })
      }

      for (let i = 6; i < 24; i++) { //开始时间小时 6-24
        let num = i < 10 ? `0${i}` : `${i}`
        this.startTimeData.push({
          value: num,
          label: num,
          children: minutes,
        })
      }
    },
    mounted() {
      this.getClassSchedules();
    },
    methods: {
      //获取老师课程计划
      getClassSchedules() {
        this.$axios.post(this.getTeacherClassSchedules, {}, {
          baseURL: apiBase3(),
        }).then(res => {
          this.scheduleList = res.data.data;
        }).catch(error => {
          console.log(error);
        })
      },
      // 点击排课，显示弹窗
      arrangeClasses(id) {
        this.startTimeValue = [];
        this.openClass = true;
        this.isCheck = true;
        this.isLoad = false;
        this.formValidate = {//初始化
          id: id,
          class_planned_date: "",
          class_planned_start_time: "",
          class_planned_end_time: "",
          duration: ""
        };
      },
      isClick(value) {  // 表单验证正确，排课按钮变蓝
        console.log(value);
        if (Array.isArray(value)) {
          Object.assign(this.formValidate, {
            class_planned_start_time: value.join(':')
          })
        }
        // let objectArray = Object.values(this.formValidate);//返回属性值的数组
        // this.isCheck = objectArray.includes("") ? true : false;
        if (this.formValidate.duration && this.formValidate.class_planned_date && this.formValidate.class_planned_start_time) {
          this.isCheck = false;
        }
      },
      // 点击排课
      handleSubmit() {
        this.loadingPaike = true;
        let date = this.formValidate.class_planned_date;
        let formatDate = this.moment(date).format('YYYY-MM-DD');
        let times = this.formValidate.class_planned_start_time;
        let dateTime = formatDate + " " + times;
        let chooseTime = this.moment(dateTime).format('x');
        let endDate = this.moment(dateTime).add(Number(this.formValidate.duration), 'm');
        let endHour = endDate.hour() < 10 ? `0${endDate.hour()}` : `${endDate.hour()}`;
        let endMinute = endDate.minute() < 10 ? `0${endDate.minute()}` : `${endDate.minute()}`;
        this.formValidate.class_planned_date = formatDate;
        // this.formValidate.class_planned_end_time = endHour + ":" + endMinute;
        // console.log(this.formValidate.class_planned_end_time);
        timestamp().then(res => {
          let nowTime = res.timestamp;
          if (chooseTime < nowTime) {
            this.$Notice.error({
              title: '提示',
              desc: '选择时间已经超过当前时间，无法排课！',
              duration: 5,
            });
            this.loadingPaike = false
            this.isCheck = false;
          } else if ((endHour > 0 && endHour < 6) || (endHour == 0 && endMinute > 0)) {
            this.$Notice.error({
              title: '提示',
              desc: '结束时间不能超过24点！',
              duration: 5,
            });
            this.loadingPaike = false
            this.isCheck = false;
          } else {
            this.isLoad = true;
            this.isCheck = true;
            // let formItem = JSON.parse(JSON.stringify(this.formItem));
            // Object.assign(formItem, {
            //   courseDate: formatDate,
            //   courseLength: Number(formItem.courseLength)
            // })
            this.$axios.post(this.courseScheduling, this.formValidate, {
              baseURL: apiBase3(),
            }).then(res => {
              this.loadingPaike = false
              this.openClass = false;
              const {data: {code, message, status} = {}} = res;
              if (+code === 200 && status === 'success') {
                this.$Message.success(message || '排课成功！');
              } else {
                this.$Message.error(message || '排课失败！');
              }
            }).catch(error => {
              this.$Message.error('排课失败！');
              this.openClass = false;
              this.loadingPaike = false
            });
          }
        });
      },

      // 批量排课
      // 点击批量排课，显示弹窗
      batchSchedule(id) {
        this.batchScheduling = true;
        this.batchValidate = {//初始化
          class_schedule_id: id,
          date: [],
          date_range_left: "",
          date_range_right: "",
          weeks: [{
            day_of_week: "",
            start_time: [],
            duration: ""
          }]
        };
      },
      handleSubmit2(name) {
        this.$refs[name].validate(async valid => {
          if (valid) {
            let batchValidate = JSON.parse(JSON.stringify(this.batchValidate));
            delete batchValidate.date
            batchValidate.weeks.forEach((item, index) => {
              item.start_time = item.start_time.join(':')
            })
            this.$axios.post(this.batchCourse, batchValidate, {
              baseURL: apiBase3(),
            }).then(res => {
              this.$Message.success(res.data.data || '批量排课成功！');
              this.batchScheduling = false;
            }).catch(error => {
              // this.$Message.error(error.response.data.message || '批量排课失败！');
            });
          }
        });
      },
      addClass() {//增加课次
        this.batchValidate.weeks.push({
          day_of_week: "",
          start_time: [],
          duration: ""
        })
      },
      deleteClass(index) {//删除课次
        if (this.batchValidate.weeks.length <= 1) {
          this.$Notice.error({
            title: '提示',
            desc: '不能再删除了！',
            duration: 5,
          });
        }
        else {
          this.batchValidate.weeks.splice(index, 1);
          console.log(this.batchValidate.weeks);
        }
      },
      //课次记录
      classRecord(id) {//课次记录
        this.$router.push({
          path: "/courseManage/classRecord",
          query: {id: id}
        });
      },


      getStudents() { // 获取该老师的学生列表
        this.$axios.post(this.getStudentsUrl, {}, {
          baseURL: apiBase2(),
        }).then(({data}) => {
          this.studentsList = data.data;
        })
      },
      // 点击排课，显示弹窗
      openClasses({
                    courseOrderUuid,
                    courseRequestUuid,
                    coursePayRequestUuid,
                    leadsUuid,
                    crUuid,
                  }) {
        this.startTimeValue = [];
        this.openClass = true;
        this.isCheck = true;
        this.isLoad = false;
        Object.assign(this.formItem, {
          courseDate: '',
          courseStartTime: '',
          courseLength: '',
          courseOrderUuid: courseOrderUuid,
          courseRequestUuid: courseRequestUuid,
          crUuid: crUuid || null,
          leadsUuid: leadsUuid,
          coursePayRequestUuid: coursePayRequestUuid || null,
        })
      },
      isClick2(value) {  // 表单验证正确，排课按钮变蓝
        console.log(value);
        if (Array.isArray(value)) {
          Object.assign(this.formItem, {
            courseStartTime: value.join(':')
          })
        }
        let objectArray = Object.values(this.formItem);
        this.isCheck = objectArray.includes("") ? true : false;
      },
    },
  }
</script>

